package com.company.aicrawlers.controller.api;

import com.company.aicrawlers.common.dto.ApiResponse;
import com.company.aicrawlers.dto.AnalysisTaskVO;
import com.company.aicrawlers.entity.AnalysisProductDetail;
import com.company.aicrawlers.entity.AnalysisQuestionResult;
import com.company.aicrawlers.entity.AnalysisTask;
import com.company.aicrawlers.entity.AnalysisTaskSummary;
import com.company.aicrawlers.service.AnalysisQueryService;
import com.company.aicrawlers.service.AnalysisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分析模块API控制器
 *
 * @author AI Crawlers Team
 * @date 2025-10-11
 */
@Slf4j
@RestController
@RequestMapping("/api/analysis")
@CrossOrigin
public class AnalysisController {

    @Autowired
    private AnalysisService analysisService;

    @Autowired
    private AnalysisQueryService queryService;

    /**
     * 获取所有分析任务列表（带汇总信息）
     *
     * @return 分析任务列表
     */
    @GetMapping("/tasks")
    public ApiResponse<List<AnalysisTaskVO>> getAnalysisTasks() {
        log.info("查询分析任务列表");
        try {
            List<AnalysisTaskVO> tasks = queryService.getAnalysisTaskList();
            return ApiResponse.success(tasks);
        } catch (Exception e) {
            log.error("查询分析任务列表失败", e);
            return ApiResponse.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 创建分析任务（对采集任务进行分析）
     *
     * @param collectTaskId 采集任务ID
     * @return 分析任务ID
     */
    @PostMapping("/create")
    public ApiResponse<Long> createAnalysis(@RequestParam Long collectTaskId) {
        log.info("接收到分析请求：collectTaskId={}", collectTaskId);
        try {
            Long analysisId = analysisService.analyze(collectTaskId);
            return ApiResponse.success(analysisId, "分析任务创建成功");
        } catch (Exception e) {
            log.error("创建分析失败", e);
            return ApiResponse.error("分析失败：" + e.getMessage());
        }
    }

    /**
     * 删除分析任务
     *
     * @param analysisId 分析ID
     * @return 删除结果
     */
    @DeleteMapping("/{analysisId}")
    public ApiResponse<Void> deleteAnalysis(@PathVariable Long analysisId) {
        log.info("删除分析任务：analysisId={}", analysisId);
        try {
            analysisService.deleteAnalysis(analysisId);
            return ApiResponse.success(null, "删除成功");
        } catch (Exception e) {
            log.error("删除分析失败", e);
            return ApiResponse.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 查询分析任务状态
     *
     * @param analysisId 分析ID
     * @return 分析任务
     */
    @GetMapping("/task/{analysisId}")
    public ApiResponse<AnalysisTask> getAnalysisTask(@PathVariable Long analysisId) {
        log.info("查询分析任务：analysisId={}", analysisId);
        AnalysisTask task = queryService.getAnalysisTask(analysisId);
        if (task == null) {
            return ApiResponse.error("分析任务不存在");
        }
        return ApiResponse.success(task);
    }

    /**
     * 查询任务汇总（模块1）
     *
     * @param analysisId 分析ID
     * @return 任务汇总数据
     */
    @GetMapping("/summary/{analysisId}")
    public ApiResponse<AnalysisTaskSummary> getTaskSummary(@PathVariable Long analysisId) {
        log.info("查询任务汇总：analysisId={}", analysisId);
        AnalysisTaskSummary summary = queryService.getTaskSummary(analysisId);
        if (summary == null) {
            return ApiResponse.error("任务汇总不存在");
        }
        return ApiResponse.success(summary);
    }

    /**
     * 查询商品列表（模块2）
     *
     * @param analysisId 分析ID
     * @return 商品分析列表
     */
    @GetMapping("/products/{analysisId}")
    public ApiResponse<List<AnalysisProductDetail>> getProductList(@PathVariable Long analysisId) {
        log.info("查询商品列表：analysisId={}", analysisId);
        List<AnalysisProductDetail> products = queryService.getProductList(analysisId);
        return ApiResponse.success(products);
    }

    /**
     * 查询商品详情（模块2）
     *
     * @param analysisId 分析ID
     * @param productId  商品ID
     * @return 商品分析详情
     */
    @GetMapping("/products/{analysisId}/{productId}")
    public ApiResponse<AnalysisProductDetail> getProductDetail(
            @PathVariable Long analysisId,
            @PathVariable Long productId) {
        log.info("查询商品详情：analysisId={}, productId={}", analysisId, productId);
        AnalysisProductDetail detail = queryService.getProductDetail(analysisId, productId);
        if (detail == null) {
            return ApiResponse.error("商品分析不存在");
        }
        return ApiResponse.success(detail);
    }

    /**
     * 查询问句列表（模块3）
     *
     * @param analysisId 分析ID
     * @return 问句分析列表
     */
    @GetMapping("/questions/{analysisId}")
    public ApiResponse<List<AnalysisQuestionResult>> getQuestionList(@PathVariable Long analysisId) {
        log.info("查询问句列表：analysisId={}", analysisId);
        List<AnalysisQuestionResult> questions = queryService.getQuestionList(analysisId);
        return ApiResponse.success(questions);
    }

    /**
     * 查询问句详情（模块3）
     *
     * @param analysisId 分析ID
     * @param questionId 问句ID
     * @return 问句分析详情
     */
    @GetMapping("/questions/{analysisId}/{questionId}")
    public ApiResponse<AnalysisQuestionResult> getQuestionDetail(
            @PathVariable Long analysisId,
            @PathVariable Long questionId) {
        log.info("查询问句详情：analysisId={}, questionId={}", analysisId, questionId);
        AnalysisQuestionResult result = queryService.getQuestionDetail(analysisId, questionId);
        if (result == null) {
            return ApiResponse.error("问句分析不存在");
        }
        return ApiResponse.success(result);
    }
}

